package com.example.android.commitcontent.ime.cores.utils;

import java.lang.reflect.Field;
import java.util.List;

public class JSONHelper {
    public static String objectToJSONString(Object o) {
        Field[] declaredFields = o.getClass().getDeclaredFields();
        StringBuilder str = new StringBuilder("{");
        for (int i = 0; i < declaredFields.length; i++) {
            Field declaredField = declaredFields[i];
            declaredField.setAccessible(true);
            try {
                str.append(String.format("\"%s\":\"%s\"", declaredField.getName(), declaredField.get(o)));
                if (i < declaredFields.length - 1)
                    str.append(",");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        str.append("}");
        return str.toString();
    }

    public static String listToJSONString(List<? extends Object> objects) {
        StringBuilder str = new StringBuilder("[");
        for (int i = 0; i < objects.size(); i++) {
            str.append(objectToJSONString(objects.get(i)));
            if (i < objects.size() - 1)
                str.append(",");
        }
        str.append("]");
        return str.toString();
    }

    public static String arrayToJSONString(Object... objects) {
        StringBuilder str = new StringBuilder("[");
        for (int i = 0; i < objects.length; i++) {
            str.append(objectToJSONString(objects[i]));
            if (i < objects.length - 1)
                str.append(",");
        }
        str.append("]");
        return str.toString();
    }
}
